package com.website.main.controller;

import com.website.common.vo.Tree;
import com.website.main.service.S_Admin;
import com.website.main.service.S_Role;
import com.website.mybatis.entity.SysPower;
import com.website.mybatis.entity.SysRole;
import com.website.mybatis.entity.SysUser;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/all")
public class Admin {


    @Autowired
    S_Admin service;

    @Autowired
    S_Role role;

    /**
     * 获取当前用户
     *
     * @return
     */
    @RequestMapping("/getCurrentUserInfo")
    @ResponseBody
    public Map<String, Object> getCurrentUserInfo() {
        Map<String, Object> map = new HashMap<String, Object>();
        Object user = SecurityUtils.getSubject().getPrincipal();
        if (user instanceof SysUser) {
            SysUser u = (SysUser) user;
            map.put("username", u.getName());
            SysRole r = role.getRoleById(u.getRoleId());
            Collection<SysPower> ps = r.getPowers();
            Map<Integer, Object> pp = new HashMap<Integer, Object>(ps.size());
            for (SysPower p : ps) {
                pp.put(p.getId(), p.getUrl());
            }
            map.put("powers", pp);
        } else if (user instanceof String) {
            map.put("username", user);
        }
        map.put("success", true);
        return map;
    }


    @RequestMapping("/getMenu")
    @ResponseBody
    public List<Tree> getAllMenuList() {
        Object user = SecurityUtils.getSubject().getPrincipal();
        SysUser u = (SysUser) user;
        if (Boolean.TRUE.equals(u.getAdmin())) {
            List<Tree> l = service.getAllMenuList();
            return l;
        }
        SysRole r = role.getRoleById(u.getRoleId());
        Collection<SysPower> ps = r.getPowers();
        List<Tree> l = service.getAllMenuList(ps);
        return l;
    }
}
